package Game3;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

//存储新坦克诞生的消息，包装成类，在TankClient类中利用UDP把数据传输给服务端
public class TankNewMsg {
    Tank tank;
    GamePanel gp;

    public TankNewMsg(GamePanel gp) {
        this.gp=gp;
    }

    public TankNewMsg(Tank tank) {
        this.tank=tank;
    }
    //发包
    public void send(DatagramSocket ds,String IP,int udpPort) {
        //管道输出流，把要输出的信息先输入到管道流中
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        DataOutputStream dos=new DataOutputStream(baos);
        try {
            dos.writeInt(tank.id);
            dos.writeInt(tank.x);
            dos.writeInt(tank.y);
            //枚举类型数组下标值
            dos.writeInt(tank.direction.ordinal());
            //此处暂时没有写入tank类敌友，dos.writeBoolean(tank.good);后续进行改进
        } catch (IOException e) {
            e.printStackTrace();
        }
        //把管道流中的信息转成字节类型，然后用Packet对UDP进行传输
        byte[]buf= baos.toByteArray();
        //装包
        try {
            DatagramPacket dp=new DatagramPacket(buf,0,buf.length,new InetSocketAddress(IP,udpPort));
            ds.send(dp);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //拆包
    public void parse(DataInputStream dis) {
        try {
            int id=dis.readInt();
            //如果传过来的ID就是该坦克，则没必要拆包
            if(gp.playerOne.id==id) {
                return;
            }
            int x=dis.readInt();
            int y=dis.readInt();
            Direction dir= Direction.values()[dis.readInt()];//貌似没有读取的必要，默认生成坦克方向向上
            //System.out.println("id:" + id + "-x:" + x + "-y:" + y + "-dir:" + dir );
            PlayerOne playerOne = new PlayerOne("images/player1/p1tankU.gif", x, y,
                    "images/player1/p1tankU.gif","images/player1/p1tankD.gif",
                    "images/player1/p1tankL.gif","images/player1/p1tankR.gif",gp);
            playerOne.id=id;
            gp.tankList.add(playerOne);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
